package com.onlyphoto.onlymall.mvp.view.activity

import android.annotation.SuppressLint
import android.os.Handler
import android.os.Message
import android.text.TextUtils
import android.view.View
import com.alipay.sdk.app.PayTask
import com.onlyphoto.onlymall.BuildConfig
import com.onlyphoto.onlymall.MyApplication
import com.onlyphoto.onlymall.R
import com.onlyphoto.onlymall.alipay.PayResult
import com.onlyphoto.onlymall.base.BaseActivity
import com.onlyphoto.onlymall.bean.response.WxPayParamsBean
import com.onlyphoto.onlymall.events.PaySuccessEvent
import com.onlyphoto.onlymall.listeners.NoDoubleClickListener
import com.onlyphoto.onlymall.mvp.contract.CPayMethod
import com.onlyphoto.onlymall.mvp.presenter.PPayMethodImpl
import com.onlyphoto.onlymall.utils.ToastUtil
import com.tencent.mm.opensdk.modelpay.PayReq
import kotlinx.android.synthetic.main.activity_paymethod.*
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode


class PayMethodActivity : BaseActivity<PPayMethodImpl>(), CPayMethod.IVPayMethod {

    private val SDK_PAY_FLAG = 1
    var orderId = ""
    var orderPrice = 0.0

    override fun retry() {}

    @SuppressLint("SetTextI18n")
    override fun init() {
        orderId = intent.getStringExtra("orderId")!!
        orderPrice = intent.getDoubleExtra("payPrice", 0.0)
        pay.text = "支付 ¥ $orderPrice"
    }

    override fun initListener() {
        back.setOnClickListener{
            finish()
        }

        pay.setOnClickListener(object :NoDoubleClickListener(){
            override fun onNoDoubleClick(view: View?) {
                if (wxpay.isChecked) {
                    wxPay()
                } else {
                    aliPay()
                }
            }
        })
    }

    override fun getWxPayParamsSuccess(bean: WxPayParamsBean) {
        //调起微信支付
        val request = PayReq()
        request.appId = BuildConfig.WEIXIN_APPID
        request.partnerId = bean.partnerid
        request.prepayId = bean.prepayid
        request.packageValue = bean.packageValue
        request.nonceStr = bean.noncestr
        request.timeStamp = bean.timestamp
        request.sign = bean.sign
        request.signType = bean.signtype
        MyApplication.api!!.sendReq(request)
    }

    override fun getAliPayParamsSuccess(params: String) {
        //调起支付宝支付
        val payRunnable = Runnable {
            val alipay = PayTask(this)
            val result = alipay.payV2(params, true)

            val msg = Message()
            msg.what = SDK_PAY_FLAG
            msg.obj = result
            mHandler.sendMessage(msg)
        }

        // 必须异步调用
        val payThread = Thread(payRunnable)
        payThread.start()
    }
    /**
     * 拿到后台返回的微信支付参数
     */
    private fun wxPay() {
        mPresenter?.getWxPayParams(orderId)
    }

    /**
     * 拿到后台返回的支付宝支付参数
     */
    private fun aliPay() {
        mPresenter?.getAliPayParams(orderId)
    }

    @SuppressLint("HandlerLeak")
    private val mHandler = object : Handler() {
        override fun handleMessage(msg: Message) {
            when (msg.what) {
                SDK_PAY_FLAG -> {
                    val payResult = PayResult(msg.obj as Map<String, String>)
                    /**
                     * 对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    val resultInfo = payResult.result// 同步返回需要验证的信息
                    val resultStatus = payResult.resultStatus
                    // 判断resultStatus 为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, "9000")) {
                        // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
                        ToastUtil.showToast("支付成功！")
                        EventBus.getDefault().post(PaySuccessEvent())
                        finish()
                    } else {
                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                        ToastUtil.showToast("支付失败！$resultInfo")
                    }
                }
            }
        }
    }

    override fun loadData() {
    }

    override fun isFullScreen(): Boolean {
        //是否沉浸式， 默认非沉浸式
        return false
    }

    public override fun initCustomerStatusManager() {
    }

    override fun setContentViewId(): Int {
        return R.layout.activity_paymethod
    }

    override fun createPresenter() {
        mPresenter = PPayMethodImpl(mContext, this)
    }

    override fun showLoading() {

    }

    override fun hideLoading() {

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onMessageEvent(event: PaySuccessEvent) {
        finish()
    }

}
